require('js/lib/require_patch').monkeypatch(this); // android needs this. Apparently there are different contexts

/**
 * @author Mark Rosenthal
 */
ui = require('js/ui/common/ui');

exports.ProviderSelectorWin = function(providerId) {
	var provider = {};
	var instance = ui.window('Provider Selection', {backgroundColor: '#000'});

	// Retrieve providers
	var providers = globals.db.listProviders();

	var providerList = Ti.UI.createTableView({data: providers, headerTitle: 'Who are you?'});
	
	var dialog;
	if (providerId) {
		for (var i=0, l=providers.length; i<l; i++) {
			if (providerId === providers[i].id) {
				provider = providers[i];
				break;
			}
		}
		// Verify Provider
		dialog = Titanium.UI.createOptionDialog({
		    title: 'Are you ' + provider.title,
		    options: ['Yes','No'],
		    cancel:1
		});
		dialog.addEventListener('click', function(e) {
			Ti.API.debug('Selected Index is: ' + e.index);
			if (e.index == 0) {
				for (var i=0, l=providers.length; i<l; i++) {
					if (providerId === providers[i].id) {
						providerList.fireEvent('click',{index:i, rowData: provider});
						break;
					}
				} 
			}
		});
	}
	
	providerList.addEventListener('click', function(e) {
		Ti.API.debug('Setting Provider Id: ' + e.rowData.id);
		globals.provider = e.rowData;
		Ti.App.Properties.setInt('providerId',globals.provider.id);
		Ti.App.fireEvent('app.provider.change',	{});	
		instance.close();
	});
	
	instance.addChild(providerList);
	
	instance.addEventListener('open',function(e){
		if (dialog)
			dialog.show();		
	});
	
	
Ti.API.debug('ProviderSelectorWin return');
	return instance;
}